// 管理员案件详情页面
const auth = require('../../../../utils/auth')
const request = require('../../../../utils/request')
const minLivingAllowanceAPI = require('../../../../api/minLivingAllowance')

Page({
  data: {
    userInfo: {},
    // 全局加载状态
    globalLoading: false,
    globalLoadingText: '管理数据加载中...',
    caseId: '',
    caseInfo: null,
    loading: true,
    // 操作相关
    showActionSheet: false,
    actionOptions: [
      { text: '通过', value: 'approve', color: '#059669' },
      { text: '驳回', value: 'reject', color: '#dc2626' }
    ],
    // 操作确认弹窗相关
    showActionModal: false,
    actionModalTitle: '',
    actionComment: '',
    currentAction: '',
    // 按钮状态
    hasOperated: false,
    buttonText: '操作'
  },

  // 显示全局加载
  showGlobalLoading(text = '管理数据加载中...') {
    const app = getApp()
    app.showGlobalLoading({
      loadingText: text
    })
  },

  // 隐藏全局加载
  hideGlobalLoading() {
    const app = getApp()
    app.hideGlobalLoading()
  },

  // 更新全局加载状态
  updateGlobalLoading(data) {
    this.setData({
      globalLoading: data.globalLoading,
      globalLoadingText: data.globalLoadingText || this.data.globalLoadingText
    })
  },

  onLoad(options) {
    // 显示页面加载效果
    this.showGlobalLoading('管理数据加载中...')
    const { id } = options
    console.log('页面参数:', options)
    console.log('获取到的ID:', id)
    
    if (!id) {
      wx.showToast({
        title: '参数错误',
        icon: 'none'
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
      return
    }

    this.setData({ caseId: id })
    console.log('设置caseId为:', id)
    this.loadUserInfo()
    this.loadCaseDetail()
  },

  onShow() {
    this.loadCaseDetail()
  },

  // 加载用户信息
  loadUserInfo() {
    const role = auth.getCurrentRole()
    if (!role || role !== 'admin') {
      wx.showToast({
        title: '权限不足',
        icon: 'none'
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
      return
    }
    
    const userInfo = auth.getCurrentUser() || {}
    console.log('当前用户信息:', userInfo)
    this.setData({ userInfo })
  },

  // 加载案件详情
  loadCaseDetail() {
    this.setData({ loading: true })
    
    // 检查caseId是否存在
    if (!this.data.caseId) {
      console.error('caseId不存在，无法加载案件详情')
      wx.showToast({
        title: '案件ID不存在',
        icon: 'none'
      })
      this.setData({ loading: false })
      this.hideGlobalLoading()
      return
    }
    
    // 获取用户信息
    const userInfo = auth.getCurrentUser()
    const userId = userInfo ? userInfo.userId : null
    const userRole = userInfo ? userInfo.role : 'admin'
    
    if (!userId) {
      wx.showToast({
        title: '用户信息获取失败',
        icon: 'none'
      })
      this.setData({ loading: false })
      this.hideGlobalLoading()
      return
    }

    // 调用API获取申请详情
    console.log('API调用参数:', {
      caseId: this.data.caseId,
      userId: userId,
      userRole: userRole
    })
    minLivingAllowanceAPI.getApplicationDetailInfo(this.data.caseId, userId, userRole)
      .then(res => {
        console.log('API响应:', res)
        
        if (res.success) {
          const applicationData = res.data.applicationInfo
          
          // 将API数据转换为页面需要的格式
          const caseInfo = this.formatApplicationToCase(applicationData, res.data)
          
          // 检查案件是否已经被操作过
          const hasOperated = caseInfo.status !== 'pending'
          const buttonText = hasOperated ? '重新处理' : '操作'
          
          this.setData({
            caseInfo: caseInfo,
            loading: false,
            hasOperated: hasOperated,
            buttonText: buttonText
          })
          
          // 隐藏全局加载状态
          this.hideGlobalLoading()
        } else {
          throw new Error(res.message || '获取申请详情失败')
        }
      })
      .catch(error => {
        console.error('获取申请详情失败:', error)
        
        this.setData({ loading: false })
        
        // 隐藏全局加载状态
        this.hideGlobalLoading()
        
        wx.showToast({
          title: error.message || '获取数据失败',
          icon: 'none',
          duration: 2000
        })
      })
  },

  // 将API数据转换为案件格式
  formatApplicationToCase(applicationData, fullData) {
    return {
      id: applicationData.id,
      title: applicationData.title,
      description: applicationData.description,
      type: 'application',
      category: 'civil-affairs',
      subCategory: 'min-income',
      status: applicationData.status,
      user: {
        name: applicationData.applicantName,
        phone: applicationData.applicantPhone,
        idCard: applicationData.applicantIdCard,
        address: applicationData.applicantAddress
      },
      formData: {
        name: applicationData.applicantName,
        idCard: applicationData.applicantIdCard,
        applicationNo: applicationData.applicationNo,
        phone: applicationData.applicantPhone,
        address: applicationData.applicantAddress,
        familySize: applicationData.familySize.toString(),
        monthlyIncome: applicationData.monthlyIncome.toString(),
        incomeSource: applicationData.incomeSource,
        reason: applicationData.difficultyReason,
        // 添加审核意见字段
        reviewComment: applicationData.reviewComment,
        processComment: applicationData.processComment
      },
      createTime: applicationData.applyTime,
      updateTime: applicationData.updatedAt,
      assignee: applicationData.reviewerName || null,
      deadline: applicationData.deadline,
      attachments: this.formatAttachments(applicationData.attachments),
      comments: this.formatComments(fullData.processLog),
      processLog: this.formatProcessLog(fullData.processLog)
    }
  },

  // 格式化附件数据
  formatAttachments(attachments) {
    if (!attachments || !Array.isArray(attachments)) {
      return []
    }
    
    return attachments.map(attachment => ({
      name: attachment.name,
      url: attachment.url,
      size: attachment.size
    }))
  },

  // 格式化评论数据
  formatComments(processLog) {
    if (!processLog || !Array.isArray(processLog)) {
      return []
    }
    
    return processLog.map(log => ({
      id: log.id,
      content: log.comment,
      author: log.operator,
      createTime: log.time
    }))
  },

  // 格式化处理日志
  formatProcessLog(processLog) {
    if (!processLog || !Array.isArray(processLog)) {
      return []
    }
    
    return processLog.map(log => ({
      action: log.action,
      operator: log.operator,
      time: log.time,
      status: log.status
    }))
  },

  // 生成案件详情数据
  generateMockCaseDetail(caseId) {
    console.log('生成案件详情数据，案件ID:', caseId)
    
    // 根据案件ID生成对应的详情数据
    const caseTypes = {
      'case_': {
        title: '最低生活保障申请',
        description: '申请人因家庭收入低于当地最低生活保障标准，申请最低生活保障',
        type: 'application',
        category: 'civil-affairs',
        subCategory: 'min-income',
        status: 'pending',
        user: {
          name: '张三',
          phone: '13812345678',
          idCard: '320123199001011234',
          address: '江苏省南京市江宁区某某村123号'
        },
        formData: {
          name: '张三',
          idCard: '320123199001011234',
          phone: '13812345678',
          address: '江苏省南京市江宁区某某村123号',
          familySize: '3',
          monthlyIncome: '1200',
          incomeSource: '务农收入',
          reason: '家庭主要劳动力因病丧失劳动能力，收入微薄，生活困难'
        },
        createTime: '2024-01-15T10:30:00.000Z',
        updateTime: '2024-01-15T10:30:00.000Z',
        assignee: null,
        deadline: '2024-01-22T10:30:00.000Z',
        attachments: [
          {
            name: '身份证复印件.jpg',
            url: '/attachments/id_card.jpg',
            size: '2.5MB'
          },
          {
            name: '收入证明.pdf',
            url: '/attachments/income_proof.pdf',
            size: '1.2MB'
          }
        ],
        comments: [
          {
            id: 'comment_1',
            content: '已收到申请材料，正在审核中',
            author: '管理员',
            createTime: '2024-01-15T11:00:00.000Z'
          }
        ],
        processLog: [
          {
            action: '提交申请',
            operator: '张三',
            time: '2024-01-15T10:30:00.000Z',
            status: 'pending'
          }
        ]
      },
      'complaint_': {
        title: '道路损坏投诉',
        description: '村内主干道路面破损严重，影响村民出行安全',
        type: 'complaint',
        category: 'infrastructure',
        status: 'pending',
        user: {
          name: '李四',
          phone: '13987654321',
          idCard: '320123198502151234',
          address: '江苏省南京市江宁区某某村456号'
        },
        formData: {
          complaintType: '基础设施',
          location: '村内主干道',
          description: '道路路面多处破损，坑洼不平，雨天积水严重',
          urgency: '高'
        },
        createTime: '2024-01-15T10:30:00.000Z',
        updateTime: '2024-01-15T10:30:00.000Z',
        assignee: null,
        deadline: '2024-01-22T10:30:00.000Z',
        attachments: [
          {
            name: '道路损坏照片.jpg',
            url: '/attachments/road_damage.jpg',
            size: '3.2MB'
          }
        ],
        comments: [
          {
            id: 'comment_1',
            content: '已收到投诉，正在安排人员现场查看',
            author: '管理员',
            createTime: '2024-01-15T11:00:00.000Z'
          }
        ],
        processLog: [
          {
            action: '提交投诉',
            operator: '李四',
            time: '2024-01-15T10:30:00.000Z',
            status: 'pending'
          }
        ]
      }
    }

    // 根据案件ID前缀返回对应类型的案件
    for (const [prefix, caseData] of Object.entries(caseTypes)) {
      if (caseId.startsWith(prefix)) {
        console.log('匹配到案件类型:', prefix)
        return {
          id: caseId,
          ...caseData
        }
      }
    }

    // 默认返回一个通用案件
    return {
      id: caseId,
      title: '案件详情',
      description: '这是一个案件详情',
      type: 'application',
      category: 'civil-affairs',
      status: 'pending',
      user: {
        name: '申请人',
        phone: '13812345678',
        idCard: '320123199001011234',
        address: '江苏省南京市江宁区某某村'
      },
      formData: {},
      createTime: new Date().toISOString(),
      updateTime: new Date().toISOString(),
      assignee: null,
      deadline: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString(),
      attachments: [],
      comments: [],
      processLog: []
    }
  },

  // 显示操作菜单
  showActionMenu() {
    this.setData({ showActionSheet: true })
  },

  // 隐藏操作菜单
  hideActionMenu() {
    this.setData({ showActionSheet: false })
  },

  // 执行操作
  onActionTap(e) {
    const { action } = e.currentTarget.dataset
    this.hideActionMenu()
    
    // 显示操作确认弹窗
    const actionTitles = {
      approve: '通过理由',
      reject: '驳回建议'
    }
    
    this.setData({
      showActionModal: true,
      actionModalTitle: actionTitles[action],
      currentAction: action,
      actionComment: ''
    })
  },

  // 隐藏操作确认弹窗
  hideActionModal() {
    this.setData({
      showActionModal: false,
      actionModalTitle: '',
      actionComment: '',
      currentAction: ''
    })
  },

  // 防止弹窗关闭
  preventClose() {
    // 空函数，用于阻止事件冒泡
  },

  // 输入操作意见
  onActionCommentInput(e) {
    this.setData({ actionComment: e.detail.value })
  },

  // 确认操作
  confirmAction() {
    const { currentAction, actionComment } = this.data
    
    if (!actionComment.trim()) {
      wx.showToast({
        title: '请输入处理意见',
        icon: 'none'
      })
      return
    }

    this.hideActionModal()
    
    // 根据操作类型执行相应逻辑
    switch(currentAction) {
      case 'approve':
        this.executeApprove(actionComment)
        break
      case 'reject':
        this.executeReject(actionComment)
        break
    }
  },

  // 执行通过操作
  executeApprove(comment) {
    this.reviewApplication('approve', comment)
  },

  // 执行驳回操作
  executeReject(comment) {
    this.reviewApplication('reject', comment)
  },

  // 调用API审核申请
  reviewApplication(action, comment) {
    const userInfo = auth.getCurrentUser()
    if (!userInfo) {
      wx.showToast({
        title: '用户信息获取失败',
        icon: 'none'
      })
      return
    }

    // 显示加载提示
    // 构建API请求数据
    const reviewData = {
      applicationId: parseInt(this.data.caseId),
      action: action,
      comment: comment,
      operatorId: userInfo.userId,
      operatorName: userInfo.name || '管理员'
    }

    console.log('审核申请数据:', reviewData)

    // 调用API
    minLivingAllowanceAPI.reviewApplication(reviewData)
      .then(res => {
        console.log('审核API响应:', res)
        if (res.success) {
          // 更新本地数据
          this.updateCaseStatusAfterAPI(res.data.status, comment, action === 'approve' ? '通过' : '驳回')
          
          wx.showToast({
            title: action === 'approve' ? '通过成功' : '驳回成功',
            icon: 'success'
          })
        } else {
          throw new Error(res.message || '操作失败')
        }
      })
      .catch(error => {
        console.error('审核申请失败:', error)
        wx.showToast({
          title: error.message || '操作失败',
          icon: 'none',
          duration: 2000
        })
      })
  },

  // API调用后更新案件状态
  updateCaseStatusAfterAPI(status, comment, action) {
    const caseInfo = { ...this.data.caseInfo }
    
    // 根据API返回的状态更新本地状态
    const statusMap = {
      'approved': 'approved',
      'rejected': 'rejected'
    }
    
    caseInfo.status = statusMap[status] || status
    caseInfo.updateTime = new Date().toISOString()
    
    // 添加处理记录
    const newComment = {
      id: `comment_${Date.now()}`,
      content: comment,
      author: this.data.userInfo.name || '管理员',
      createTime: new Date().toISOString()
    }
    
    // 添加处理日志
    const newLog = {
      action: action,
      operator: this.data.userInfo.name || '管理员',
      time: new Date().toISOString(),
      status: caseInfo.status
    }
    
    // 如果是重新处理，只清空当前用户的操作记录，保留其他用户的记录
    if (this.data.hasOperated) {
      const currentUserName = this.data.userInfo.name || '管理员'
      
      // 过滤掉当前用户之前的操作记录，保留其他用户的记录
      caseInfo.comments = (caseInfo.comments || []).filter(comment => 
        comment.author !== currentUserName
      ).concat([newComment])
      
      caseInfo.processLog = (caseInfo.processLog || []).filter(log => 
        log.operator !== currentUserName
      ).concat([newLog])
    } else {
      // 首次处理，保留原有记录并添加新的
      caseInfo.comments = [...(caseInfo.comments || []), newComment]
      caseInfo.processLog = [...(caseInfo.processLog || []), newLog]
    }
    
    // 更新按钮状态
    this.setData({ 
      caseInfo,
      hasOperated: true,
      buttonText: '重新处理'
    })
  },

  // 更新案件状态（保留原方法用于兼容）
  updateCaseStatus(status, comment, action) {
    const caseInfo = { ...this.data.caseInfo }
    caseInfo.status = status
    caseInfo.updateTime = new Date().toISOString()
    
    // 添加处理记录
    const newComment = {
      id: `comment_${Date.now()}`,
      content: comment,
      author: this.data.userInfo.name || '管理员',
      createTime: new Date().toISOString()
    }
    
    // 添加处理日志
    const newLog = {
      action: action,
      operator: this.data.userInfo.name || '管理员',
      time: new Date().toISOString(),
      status: status
    }
    
    // 如果是重新处理，只清空当前用户的操作记录，保留其他用户的记录
    if (this.data.hasOperated) {
      const currentUserName = this.data.userInfo.name || '管理员'
      
      // 过滤掉当前用户之前的操作记录，保留其他用户的记录
      caseInfo.comments = (caseInfo.comments || []).filter(comment => 
        comment.author !== currentUserName
      ).concat([newComment])
      
      caseInfo.processLog = (caseInfo.processLog || []).filter(log => 
        log.operator !== currentUserName
      ).concat([newLog])
    } else {
      // 首次处理，保留原有记录并添加新的
      caseInfo.comments = [...(caseInfo.comments || []), newComment]
      caseInfo.processLog = [...(caseInfo.processLog || []), newLog]
    }
    
    // 更新按钮状态
    this.setData({ 
      caseInfo,
      hasOperated: true,
      buttonText: '重新处理'
    })
  },

  // 查看附件
  viewAttachment(e) {
    console.log('=== 开始查看附件 ===')
    const { url, name } = e.currentTarget.dataset
    console.log('原始数据:', { url, name })
    
    if (!url) {
      console.log('URL为空，显示错误提示')
      wx.showToast({
        title: '文件路径无效',
        icon: 'none'
      })
      return
    }

    // 格式化URL，处理相对路径
    const fullUrl = this.formatAttachmentUrl(url)
    console.log('格式化后的URL:', fullUrl)
    
    // 判断文件类型 - 优先从URL获取扩展名，其次从文件名
    let fileExtension = ''
    if (fullUrl) {
      const urlParts = fullUrl.split('.')
      if (urlParts.length > 1) {
        fileExtension = urlParts[urlParts.length - 1].toLowerCase()
      }
    }
    if (!fileExtension && name) {
      fileExtension = name.split('.').pop().toLowerCase()
    }
    console.log('文件扩展名:', fileExtension)
    console.log('文件名:', name)
    console.log('URL:', fullUrl)
    
    const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']
    
    if (imageExtensions.includes(fileExtension)) {
      console.log('检测到图片文件，使用 wx.previewImage')
      
      // 先检查图片URL是否可访问
      wx.request({
        url: fullUrl,
        method: 'HEAD',
        success: (res) => {
          console.log('图片URL检查成功:', res.statusCode)
          if (res.statusCode === 200) {
            // 预览图片
            wx.previewImage({
              urls: [fullUrl],
              current: fullUrl,
              success: () => {
                console.log('图片预览成功')
              },
              fail: (error) => {
                console.error('图片预览失败:', error)
                // 如果预览失败，尝试下载后预览
                this.downloadAndPreviewImage(fullUrl, name)
              }
            })
          } else {
            console.log('图片URL不可访问，状态码:', res.statusCode)
            wx.showToast({
              title: '图片无法访问',
              icon: 'none'
            })
          }
        },
        fail: (error) => {
          console.error('图片URL检查失败:', error)
          // 如果检查失败，直接尝试预览
          wx.previewImage({
            urls: [fullUrl],
            current: fullUrl,
            success: () => {
              console.log('图片预览成功')
            },
            fail: (previewError) => {
              console.error('图片预览失败:', previewError)
              // 如果预览失败，尝试下载后预览
              this.downloadAndPreviewImage(fullUrl, name)
            }
          })
        }
      })
    } else {
      console.log('检测到文档文件，使用 wx.downloadFile + wx.openDocument')
      // 预览文档
      wx.downloadFile({
        url: fullUrl,
        success: (res) => {
          console.log('文件下载成功:', res)
          if (res.statusCode === 200) {
            wx.openDocument({
              filePath: res.tempFilePath,
              fileType: fileExtension,
              success: () => {
                console.log('文档预览成功')
              },
              fail: (error) => {
                console.error('文档预览失败:', error)
                wx.showToast({
                  title: '文档预览失败',
                  icon: 'none'
                })
              }
            })
          } else {
            console.log('下载失败，状态码:', res.statusCode)
            wx.showToast({
              title: '文件下载失败',
              icon: 'none'
            })
          }
        },
        fail: (error) => {
          console.error('文件下载失败:', error)
          wx.showToast({
            title: '文件下载失败',
            icon: 'none'
          })
        }
      })
    }
    console.log('=== 查看附件结束 ===')
  },

  // 下载并预览图片
  downloadAndPreviewImage(url, name) {
    console.log('开始下载图片:', url)
    wx.downloadFile({
      url: url,
      success: (res) => {
        console.log('图片下载成功:', res)
        if (res.statusCode === 200) {
          // 下载成功后预览图片
          wx.previewImage({
            urls: [res.tempFilePath],
            current: res.tempFilePath,
            success: () => {
              console.log('下载后图片预览成功')
            },
            fail: (error) => {
              console.error('下载后图片预览失败:', error)
              wx.showToast({
                title: '图片预览失败',
                icon: 'none'
              })
            }
          })
        } else {
          console.log('图片下载失败，状态码:', res.statusCode)
          wx.showToast({
            title: '图片下载失败',
            icon: 'none'
          })
        }
      },
      fail: (error) => {
        console.error('图片下载失败:', error)
        wx.showToast({
          title: '图片下载失败',
          icon: 'none'
        })
      }
    })
  },

  // 格式化附件URL
  formatAttachmentUrl(url) {
    if (!url) return ''
    
    console.log('原始URL:', url)
    
    // 如果已经是完整的URL，直接返回
    if (url.startsWith('http://') || url.startsWith('https://')) {
      console.log('已经是完整URL，直接返回:', url)
      return url
    }
    
    // 如果是相对路径，添加服务器地址
    if (url.startsWith('/uploads/')) {
      const app = getApp()
      const baseUrl = app.globalData.baseUrl || 'http://localhost:3000'
      const fullUrl = `${baseUrl}${url}`
      console.log('相对路径转换为完整URL:', fullUrl)
      return fullUrl
    }
    
    // 如果URL不包含协议，添加服务器地址
    if (!url.includes('://')) {
      const app = getApp()
      const baseUrl = app.globalData.baseUrl || 'http://localhost:3000'
      const fullUrl = `${baseUrl}/uploads/${url}`
      console.log('无协议URL转换为完整URL:', fullUrl)
      return fullUrl
    }
    
    // 其他情况直接返回
    console.log('其他情况，直接返回:', url)
    return url
  },

  // 联系申请人
  contactUser() {
    const phone = this.data.caseInfo.user.phone
    wx.makePhoneCall({
      phoneNumber: phone,
      success: () => {
        console.log('拨打电话成功')
      },
      fail: () => {
        wx.showToast({
          title: '拨打电话失败',
          icon: 'none'
        })
      }
    })
  },

  // 格式化时间
  formatTime(timeStr) {
    const time = new Date(timeStr)
    const now = new Date()
    const diff = now - time
    
    if (diff < 60 * 1000) {
      return '刚刚'
    } else if (diff < 60 * 60 * 1000) {
      return `${Math.floor(diff / (60 * 1000))}分钟前`
    } else if (diff < 24 * 60 * 60 * 1000) {
      return `${Math.floor(diff / (60 * 60 * 1000))}小时前`
    } else {
      return `${Math.floor(diff / (24 * 60 * 60 * 1000))}天前`
    }
  },

  // 获取状态文本
  getStatusText(status) {
    const statusMap = {
      pending: '待处理',
      approved: '已通过',
      rejected: '已驳回'
    }
    return statusMap[status] || '未知'
  },

  // 获取状态颜色
  getStatusColor(status) {
    const colorMap = {
      pending: '#dc2626',
      approved: '#059669',
      rejected: '#dc2626'
    }
    return colorMap[status] || '#64748b'
  }
})
